import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;

import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.InputStream;
import java.net.InetSocketAddress;

/**
 * 税务计算逻辑
 */
public class PersonalTaxCalculatorService {

    private static final int PORT = 8080;
    private HttpServer server;

    public void start() throws IOException {
        server = HttpServer.create(new InetSocketAddress(PORT), 0);
        server.createContext("/calculateTax", new TaxHandler());
        server.setExecutor(null);
        server.start();
        System.out.println("Server started on port " + PORT);
    }

    public void stop() {
        if (server != null) {
            server.stop(0);
            System.out.println("Server stopped");
        }
    }

    static class TaxHandler implements HttpHandler {
        private final Gson gson = new GsonBuilder().create();

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            if ("POST".equals(exchange.getRequestMethod())) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(exchange.getRequestBody()));
                TaxRequest request = gson.fromJson(reader, TaxRequest.class);
                double tax = calculateTax(request.income);
                TaxResponse response = new TaxResponse(tax);

                String jsonResponse = gson.toJson(response);
                exchange.sendResponseHeaders(200, jsonResponse.getBytes().length);
                OutputStream os = exchange.getResponseBody();
                os.write(jsonResponse.getBytes());
                os.close();
            } else {
                exchange.sendResponseHeaders(405, -1); // Method Not Allowed
            }
        }

        private static double calculateTax(double income) {
            double tax = 0;
            // Tax calculation logic (example)
            if (income <= 5000) {
                tax = 0;
            } else if (income <= 20000) {
                tax = (income - 5000) * 0.1;
            } else {
                tax = (income - 20000) * 0.2 + 1500; // Example of tax calculation
            }
            return tax;
        }
    }

    static class TaxRequest {
        double income;

        public TaxRequest(double income) {
            this.income = income;
        }
    }

    static class TaxResponse {
        double tax;

        public TaxResponse(double tax) {
            this.tax = tax;
        }
    }
}
